import classnames from 'classnames'
import { useNavigate } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/component/icon'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { SearchAPI } from '@/api/search'
import debounce from 'lodash/debounce'
import { useDebounceFn } from 'ahooks'
// const run = debounce(async (e) => {
//   const res = await SearchAPI({ q: e })
//   console.log(res)
// }, 600)
const SearchPage = () => {
  const history = useNavigate()
  const debouncefn = useDebounceFn
  const [keyWord, setKeyWord] = useState('')
  const [suggest, setSuggest] = useState<string[]>([])
  const [searchList, setSearchList] = useState<string[]>(
    JSON.parse(localStorage.getItem('search-key') || '[]')
  )
  // 防抖
  const { run } = debouncefn(
    async (e) => {
      const res = await SearchAPI({ q: e })
      // console.log(res)
      // const _suggest = res.data.options.map((item) => {
      //   return item && item.replace(e, `<span>${e}</span>`)
      // })
      setSuggest(res.data.options)
    },
    {
      wait: 600,
    }
  )
  // 搜索
  const onsearch = async (e: string) => {
    setKeyWord(e.trim())
    if (!e.trim()) return setSuggest([])
    run(e)
  }
  //监听 储存历史记录
  useEffect(() => {
    localStorage.setItem('search-key', JSON.stringify(searchList))
  }, [searchList])
  // 搜索跳转页面
  const enter = (keyWord: string) => {
    setTimeout(() => {
      history(`/search/result?q=${keyWord}`)
    })
    if (searchList.some((item) => item === keyWord)) return
    setSearchList([...searchList, keyWord])
  }
  // 单删
  const delSearchList = (keyWord: string) => {
    const _searchList = searchList.filter((item) => item !== keyWord)
    setSearchList(_searchList)
  }
  // 全删
  const delAllSearchList = () => {
    setSearchList([])
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history(-1)}
        right={
          <span className="search-text" onClick={() => enter(keyWord)}>
            搜索
          </span>
        }>
        <SearchBar
          value={keyWord}
          onChange={onsearch}
          onSearch={() => enter(keyWord)}
          placeholder="请输入关键字搜索"
        />
      </NavBar>

      {!suggest.length && (
        <div
          className="history"
          style={{
            display: searchList.length ? 'block' : 'none',
          }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={delAllSearchList}>
              <Icon iconName="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchList.map((item) => (
              <span
                className="history-item"
                key={item}
                onClick={() => enter(item)}>
                <span className="text-overflow">{item}</span>
                <Icon
                  iconName="iconbtn_essay_close"
                  onClick={(e) => {
                    e.stopPropagation()
                    delSearchList(item)
                  }}
                />
              </span>
            ))}
          </div>
        </div>
      )}
      <div
        className={classnames('search-result', suggest.length ? 'show' : '')}>
        {suggest.map(
          (item) =>
            item && (
              <div
                className="result-item"
                key={item}
                onClick={() => enter(item)}>
                <Icon className="icon-search" iconName="iconbtn_search" />
                <div
                  className="result-value text-overflow"
                  dangerouslySetInnerHTML={{
                    __html: item.replaceAll(keyWord, `<span>${keyWord}</span>`),
                  }}></div>
              </div>
            )
        )}
      </div>
    </div>
  )
}

export default SearchPage
